﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Net.Browser;
using System.Diagnostics;
using HaoLab.Library.NCEPU.Search;
using HaoLab.Library;
using System.Reactive;


namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            Touch.FrameReported += Touch_FrameReported;
            Renew re = new Renew();
            re.Do();
            
           
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                System.Uri uri = new Uri("http://202.204.72.4:8080/opac/openlink.php?strSearchType=title&historyCount=1&strText=%E6%B5%8B%E8%AF%95&x=0&y=0&doctype=ALL&match_flag=forward&displaypg=20&sort=CATA_DATE&orderby=desc&showmode=list&dept=ALL");
                // Create a HttpWebrequest object to the desired URL.
                HttpWebRequest myHttpWebRequest1 = (HttpWebRequest)WebRequest.Create(uri);
                myHttpWebRequest1.Method = "GET";
                myHttpWebRequest1.Accept = "text/html,image/png,image/*,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                myHttpWebRequest1.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1";

                // Create an instance of the RequestState and assign the previous myHttpWebRequest1
                // object to it's request field.  
                RequestState myRequestState = new RequestState();
                myRequestState.request = myHttpWebRequest1;


                // Start the asynchronous request.
                IAsyncResult result =
                  (IAsyncResult)myHttpWebRequest1.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);

            }
            catch (WebException ex)
            {
                outputBlock.Text += "\nException raised!\n";
                outputBlock.Text += "Message: ";
                outputBlock.Text += ex.Message;
                outputBlock.Text += "\nStatus: ";
                outputBlock.Text += ex.Status;
                outputBlock.Text += "\n";
            }
            catch (Exception ex)
            {
                outputBlock.Text += "\nException raised!\n";
                outputBlock.Text += "\nMessage: ";
                outputBlock.Text += ex.Message;
                outputBlock.Text += "\n";
            }

        }

        public class RequestState
        {
            // This class stores the State of the request.
            const int BUFFER_SIZE = 1024;
            public StringBuilder requestData;
            public byte[] BufferRead;
            public HttpWebRequest request;
            public HttpWebResponse response;
            public Stream streamResponse;

            public RequestState()
            {
                BufferRead = new byte[BUFFER_SIZE];
                requestData = new StringBuilder("");
                request = null;
                streamResponse = null;
            }
        }


        const int BUFFER_SIZE = 1024;
        public static ManualResetEvent allDone = new ManualResetEvent(false);


        private void RespCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                // State of request is asynchronous.
                RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
                HttpWebRequest myHttpWebRequest2 = myRequestState.request;
                myRequestState.response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asynchronousResult);

                // Read the response into a Stream object.
                Stream responseStream = myRequestState.response.GetResponseStream();
                myRequestState.streamResponse = responseStream;

                // Begin the Reading of the contents of the HTML page and print it to the console.
                IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
            }
            catch (WebException e)
            {
                // Need to handle the exception
                this.Dispatcher.BeginInvoke(() => MessageBox.Show(e.Message));
            }
        }
        private void ReadCallBack(IAsyncResult asyncResult)
        {
            try
            {

                RequestState myRequestState = (RequestState)asyncResult.AsyncState;
                Stream responseStream = myRequestState.streamResponse;
                int read = responseStream.EndRead(asyncResult);
                // Read the HTML page and then do something with it
                if (read > 0)
                {
                    GB2312.GB2312Encoding encoding = new GB2312.GB2312Encoding();
                    myRequestState.requestData.Append(Encoding.UTF8.GetString(myRequestState.BufferRead, 0, read));
                    IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
                }
                else
                {
                    if (myRequestState.requestData.Length > 1)
                    {
                        string stringContent;
                        stringContent = myRequestState.requestData.ToString();


                        // do something with the response stream here
                        this.Dispatcher.BeginInvoke(() => outputBlock.Text = stringContent);

                    }

                    responseStream.Close();
                    allDone.Set();

                }

            }
            catch (WebException e)
            {
                // Need to handle the exception
            }


        }

        private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
        }

        void Touch_FrameReported(object sender, TouchFrameEventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            // 传入null表明获取到的触控点信息是以屏幕左上角为原点的。
            var primaryPoint = e.GetPrimaryTouchPoint(null);

            if (primaryPoint != null)
            {
                // 列出主触控点的位置。
                sb.Append("Position: X:" + primaryPoint.Position.X.ToString() + " Y:" + primaryPoint.Position.Y.ToString() + "\n");

                // 列出主触控点的动作。
                sb.Append("Action: " + primaryPoint.Action.ToString() + "\n");

                // 列出主触控点的设备。
                sb.Append("TouchDeviceId: " + primaryPoint.TouchDevice.Id.ToString() + "\n");

                // 列出主触控点紧贴手指的UIElement元素。
                sb.Append("DirectlyOver: " + (primaryPoint.TouchDevice.DirectlyOver as FrameworkElement).Name + "\n");

                // 列出主触控点的区域范围信息（这个属性并不能提供有用的值）。
                sb.Append("Size: Width:" + primaryPoint.Size.Width.ToString() + " Height:" + primaryPoint.Size.Height.ToString() + "\n");

                Debug.WriteLine(sb.ToString());
            }

            // 传入null表明获取到的触控点信息是以屏幕左上角为原点的。
            var points = e.GetTouchPoints(null);

            if (points != null)
            {
                // 列出所有触控点的位置信息。
                foreach (var point in points)
                {
                    sb.Append("Position: X:" + point.Position.X.ToString() + " Y:" + point.Position.Y.ToString() + " " + point.Action.ToString() + "\n");
                }
            }

            button1.Content = sb.ToString();
        }



        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            SimpleSearch ss = new SimpleSearch();
            ss.Get();

        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PhonePage1.xaml", UriKind.Relative));
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            SimpleSearch ss = new SimpleSearch();
            ss.Find(new Action<DownloadStringCompletedEventArgs>(s =>
                {
                    Debug.WriteLine(s.Result);
                }));
        }

    }
}